package com.xing.libao.init;

import com.xing.libao.util.RequestUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * User: xingzhe
 * Date: 2015/8/17
 * Time: 15:14
 */
public class DownLogo {
    static RequestUtil requestUtil = RequestUtil.getInstance();
    public static void main(String[] args) {
        File file = new File("D:\\logo\\logo.txt");
        BufferedReader reader = null;
        try {
            System.out.println("以行为单位读取文件内容，一次读一整行：");
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                System.out.println(tempString);
                String[] logo = tempString.split("\t");
                downImg(logo[0]+"-"+logo[1]+".jpg",logo[2]);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    private static void downImg(String name,String url){
        name = name.replaceAll("\\\\|/|:|\\*|\\?|\"|<|>|\\|", "");
        File file = new File("D:\\logo\\" + name);
        try {
            if (!file.exists()) {
                if (file.createNewFile()) {
                    CloseableHttpResponse response = requestUtil.execute(new HttpGet(url));
                    if (response != null) {
                        BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream(file));
                        byte[] result = EntityUtils.toByteArray(response.getEntity());
                        bw.write(result);
                        bw.close();
                        response.close();
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
